package api

import (
	"ginfast/app/system/dto"
	"ginfast/app/system/model"
	"ginfast/app/system/service"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"ginfast/util"
)

// Menu 系统管理菜单
type Menu struct {
}

// ListHandler 菜单列表
func (Menu) ListHandler(c *ginx.Context) {
	var p dto.Where
	if err := c.MustBind(&p); err != nil {
		return
	}
	var data []model.Menu
	p.DbModelWhere(&model.Menu{}).Find(&data)
	c.JSONWriteData(data)
}

// TreeSelectHandler 列表
func (Menu) TreeSelectHandler(c *ginx.Context) {
	data := service.MenuTree(c.GetUser().RoleID)
	c.JSONWriteData(data)
}

// RoleMenuTreeHandler 角色菜单列表
func (Menu) RoleMenuTreeHandler(c *ginx.Context) {
	id := c.ParamUInt("id")
	data := service.MenuTree(id)
	c.JSONWrite(ginx.H{"menus": data})
}

// GetHandler 查询菜单详细
func (Menu) GetHandler(c *ginx.Context) {
	util.QueryByID(&model.Menu{}, c)
}

// AddHandler 新增
func (Menu) AddHandler(c *ginx.Context) {
	var p model.Menu
	err := c.MustBind(&p.MenuOpt)
	if err != nil {
		return
	}
	err = orm.DbCreate(&p)
	c.JSONWriteError(err)
}

// UpdateHandler 修改
func (Menu) UpdateHandler(c *ginx.Context) {
	var p model.Menu
	err := c.MustBind(&p.MenuOpt)
	if err != nil {
		return
	}
	err = orm.DbUpdateModel(&p)
	c.JSONWriteError(err)
}

// DeleteHandler 删除菜单
func (Menu) DeleteHandler(c *ginx.Context) {
	util.Deletes(&model.Menu{}, c)
}

func (o Menu) Routers(r *ginx.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/:id", o.GetHandler)
	r.GET("/treeselect", o.TreeSelectHandler)
	r.GET("/roleMenuTreeselect/:id", o.RoleMenuTreeHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.DELETE("/:id", o.DeleteHandler)
}
